<template>
  <div ref="manyBar" :style="{width:width,height:height}"></div>
</template>
<script>
export default {
  name: 'manyBar',
  data() {
    return {
      myChart:null,
      barData:[]
    }
  },
  components: {},

  filters: {},

  computed: {},

  created() {},
  props:{
    width:{
      type:String,
      default:""
    },
    height:{
      type:String,
      default:""
    },
    name:{
      type:Array,
      default:()=>[]
    },
    unit:{
      type:Array,
      default:()=>[]
    },
    data:{
      type:Array,
      default:()=>[]
    }
  },
  watch:{
    data:{
      handler(val){
        this.barData = val;
        this.getEchart();
      },
      deep:true
    }
  },
  activated() {},

  mounted() {
  },

  methods: {
    getEchart() {
      
      if (
        //判断是否存在echarts实例化对象,如果存在则销毁
        this.myChart != null &&
        this.myChart != '' &&
        this.myChart != undefined
      ) {
        this.myChart.dispose()
      }
      this.myChart = this.$echarts.init(this.$refs.manyBar) //创建echarts实例化对象
      let _this = this;
      let option = {
        // title: {
        //   text: 'World Population'
        // },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter:function(params){
            let relVal = params[0].name;
            params.forEach((item,i) => {
              relVal += "</br>" + item.marker + item.seriesName + "：" + item.value +  " "+ _this.unit[i]
            });
            return relVal
          },
        },
        // 保存本地
        // toolbox: {
        //   feature: {
        //     saveAsImage: { show: true }
        //   }
        // },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: [0, 0.01],
          data: this.name,
        },
        yAxis: [
          {
            type: 'value',
            name: '睡眠时长',
            position: 'left',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#999"
              }
            },
          }
        ],
        series: [
          {
            name: '总睡眠时长',
            type: 'bar',
            yAxisIndex: 0,
            data: this.barData[0],
            barWidth:15
          },
          {
            name: '深睡时长',
            type: 'bar',
            yAxisIndex: 0,
            data: this.barData[1],
            barWidth:15
          },
          {
            name: '浅睡时长',
            type: 'bar',
            yAxisIndex: 0,
            data: this.barData[2],
            barWidth:15
          }
        ]
      };
      this.myChart.setOption(option);
      window.addEventListener("resize", ()=>{
        _this.myChart.resize();
      })
    },
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>
